<?php

namespace Meeting\Controller;
use Common\Controller\FrontbaseController;
use User\Lib\PraiseLib;
use User\Lib\CommentLib;

class ApiController extends FrontbaseController{

	protected $meeting_model;
	protected $meeting_joined_model;
	protected $meeting_comment_model;

	function _initialize() {
		parent::_initialize();
		$this->meeting_model = D("Meeting");
		$this->meeting_joined_model = D("MeetingJoined");
		$this->meeting_comment_model = D("MeetingComment");
		$this->user_thumbup_model = D("User/UserThumbup");
	}

	/**
	 * 发起活动首页（获取店面名称和桌号）
	 * 注：依赖于shop模块儿
	 * @author Hongwei 2017-06-17
	 */
	public function shop_infomation(){
		$shops = \Shop\Lib\ImiLib::getShops();
		// 判断返回结果
		if ($shops) {
			$arr['status'] = '1';
			$arr['msg'] = '获取店铺信息数据 成功';
			$arr['info'] = $shops;
		} else {
			$arr['status'] = '0';
			$arr['msg'] = '获取店铺信息数据 失败！';
		}
		$this->output($arr);
	}

	/**
	 * 发起活动
	 * 注：依赖于shop模块儿
	 * @author Hongwei 2017-06-17
	 */
	public function add_meeting(){

		if (IS_POST) {
			$userInfo = session('user');        //session

			// 传参得到数据 / start
			$data['user_id'] = $userInfo['id'];                        // 用户ID
			$data['cate_id'] = I('cate_id');                            // 活动分类
			$data['meeting_title'] = I('meeting_title');                            // 活动标题
			$data['meeting_start_time'] = I('meeting_start_time');    // 聚会开始时间
			$data['meeting_end_time'] = I('meeting_end_time');    // 聚会结束时间
			$data['signup_end_time'] = I('signup_end_time');        // 报名截止日期
			$data['address_id'] = I('address_id');                        // 聚会的店名，啤咔专用，用 shop 模块儿传过来的
			$data['address_province'] = I('address_province');                // 省，（啤咔不用，华宇用）
			$data['address_city'] = I('address_city');                    // 市，（啤咔不用，华宇用）
			$data['address_name'] = I('address_name');                    // 聚会的具体地址
			$data['people_number'] = I('people_number');                    // 聚会的人数限制
			$data['people_pay_price'] = I('people_pay_price');                // 人均消费
			$data['thumbs_up_number'] = 0;                                        // 点赞的数量（用户点赞一次，这里增加一次，这里目前不需要传参数，默认为0，可根据需要设置，或者用大C写参数）
			$data['description'] = I('description');                    // 活动介绍
			$data['memo'] = I('memo');                            // 活动须知
			$data['status'] = 1;                                        // 状态,1为审核通过,0为审核不通过,这里默认通过，
			$data['create_time'] = time();                                // 发布时间
			// 传参得到数据 / end

			//上传封面/start
			$upload = new \Think\Upload();// 实例化上传类
			$upload->maxSize = 3145728;// 设置附件上传大小
			$upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
			$upload->rootPath = './' . C("UPLOADPATH"); // 设置附件上传根目录
			$upload->savePath = './meeting_big/'; // 设置附件上传（子）目录
			$upload->subName=null;

			//大图start
			$info_big = $upload->uploadOne($_FILES['poster_photo']);
			$file_path_big= './data/upload/meeting_big/'.$info_big['savename'];
			//大图end

			//缩略图start
			$file_path_small= './data/upload/meeting/'.$info_big['savename'];
			$image = new \Think\Image();
			$image->open($file_path_big);
			$info = $image->thumb(450, 150)->save($file_path_small);
			//缩略图end
			$data['poster_photo'] = $file_path_small;
			//上传封面/end

			// 增加操作
			$rst = $this->meeting_model->add($data);

			// 判断返回结果
			if ($rst) {
				$arr['status'] = '1';
				$arr['msg'] = '您已成功提交活动！';
				$arr['info'] = $rst;
			} else {
				$arr['status'] = '0';
				$arr['msg'] = '提交活动失败！';
			}
			$this->output($arr);
		}
	}

	/**
	 * 获取单个活动的数据,发起活动支付的界面-简单
	 * @author Hongwei 2017-06-17
	 */
	public  function getMeetingByid(){
		$where['meeting_id'] = I('meeting_id');
		$meeting_info = $this->meeting_model->where($where)->find();
		// 判断返回结果
		if ($meeting_info) {
			$arr['status'] = '1';
			$arr['msg'] = '获取单个活动的数据 成功！';
			$arr['info'] = $meeting_info;
		} else {
			$arr['status'] = '0';
			$arr['msg'] = '获取单个活动的数据 失败！';
		}
		$this->output($arr);
	}


	/**
	 * 聚会详情
	 * 依赖于 user 和 shop  模块儿
	 * @author Hongwei 2017-06-17
	 */
	public  function meetingDetails(){
		
		$where = array();
		
		$meeting_id = I('meeting_id/d');
		$where['meeting_id'] = $meeting_id;
		$meeting_info = $this->meeting_model->where($where)->find();
		$meeting_info['meeting_start_time'] = date('m月d日 H:i',$meeting_info['meeting_start_time']); //开始时间,5月20日 19:00
		$meeting_info['meeting_end_time'] = date('H:i',$meeting_info['meeting_end_time']);   			 //结束时间,23:00
		$meeting_info['create_time'] = date('Y-m-d H:i:s',$meeting_info['create_time']);

		// 评论数量
		$comment_count= CommentLib::comment_number(MODULE_NAME,$meeting_id);
		$meeting_info['comment_number'] = $comment_count['count'];

		// 点赞状态
	
		$i_haved_prised = \User\Lib\PraiseLib::is_praised(MODULE_NAME,$meeting_id);
		$meeting_info['thumbs_up_status'] = $i_haved_prised['status'];

		// 获取 user_id 获取“发起人”信息
		$user_id = $meeting_info['user_id'];
		$user = \User\Lib\ImiLib::getUserById($user_id);
		$meeting_info['userinfo'] = $user;

		// 获取“报名人的列表”
		$joined_people = $this->meeting_joined_model->where($where)->select();

		foreach ($joined_people as $key => $value){
			$user_id_joined = $value['user_id'];
			$user_id_avatar = \User\Lib\ImiLib::getAvatarByUserId($user_id_joined);
			$joined_people[$key]['avatar'] = $user_id_avatar['avatar'];
			$joined_people[$key]['user_joined_time'] = date('Y-m-d H:i:s',$joined_people[$key]['user_joined_time']);
		}
		$meeting_info['joined'] = $joined_people;

		// 获取店的信息,shop模块儿
		$shop_id  = $meeting_info['address_id'];;
		$meeting_info['shop'] = \Shop\Lib\ImiLib::getShopById($shop_id);

		// 判断返回结果
		if ($meeting_info) {
			$arr['status'] = '1';
			$arr['msg'] = '获取聚会详情 成功';
			$arr['info'] = $meeting_info;
		} else {
			$arr['status'] = '0';
			$arr['msg'] = '获取聚会详情 失败！';
		}
		$this->output($arr);

	}

	/**
	 * 对该聚会的点赞动作
	 * @author Hongwei 2017-06-17
	 * 点赞过的人不能再点赞
	 */
	public  function meeting_details_thumbup(){
		
		$result = false;
		$meeting_id = I('meeting_id/d');
		
		$meeting_info = $this->meeting_model->field('meeting_id,user_id')->find($meeting_id);
		
		if(!$meeting_info){
			$assign['error']	 = 101;
			$assign['error_msg'] = '没有聚会信息';
			$assign['status']	 = false;
			$this->output($assign);
		}
		
		//请求点赞接口
		$meeting_info && $data = PraiseLib::praise_object(MODULE_NAME,$meeting_id,$meeting_info['user_id']);
	
		if(!$data['error']){
			if($data['type'] == 'praise'){
				$result = true && $this->meeting_model->where(array('meeting_id'=>$meeting_id))->setInc('thumbs_up_number');
				if(!$result){
					$data['error_msg'] = '聚会表点赞数增加失败';
					$data['error'] = 101;
					unset($data['msg']);
				}
			}else if($data['type'] == 'unpraise'){
				$result = true && $this->meeting_model->where(array('meeting_id'=>$meeting_id))->setDec('thumbs_up_number');
				if(!$result){
					$data['error_msg'] = '聚会表点赞数减少失败';
					$data['error'] = 101;
					unset($data['msg']);
				}
			}
		}
		
		$this->output($data);
	}

	/**
	 * 活动列表
	 * status doing 正在进行中
	 *
	 * @author Hongwei 2017-06-17
	 */
	public  function  meeting_list($status = 'doing'){

		$start = I('start');		//开始位置
		$limit = I('limit');		//显示数量

		// 条件1 - 开始时间-结束时间
		date_default_timezone_set("PRC");
		$time = time();//当前时间
		//doing 正在进行中
		$where_doing['meeting_start_time'] 		= array('ELT',$time);  // 开始时间小于当前时间
		$where_doing['meeting_end_time']			= array('EGT',$time);  // 结束时间大于当前时间
		$where_doing['status'] = 1;
		//end 已结束
		$where_end['meeting_end_time'] 			= array('LT',$time);
		$where_end['status'] = 1;
		// notbegin 未开始
		$where_notbegin['meeting_start_time'] 	= array('GT',$time);
		$where_notbegin['status'] = 1;
		// nopass
		$where_notpass['status'] =0;

		$status == 'all'		&& $where = array(); //默认全部
		$status == 'doing' 	&& $where = $where_doing; 		// 聚会正在进行
		$status == 'end' 		&& $where = $where_end; 		// 聚会已经结束
		$status == 'notbegin'	&& $where = $where_notbegin; 	// 聚会未开始
		$status == 'notpass' 	&& $where = $where_notpass; 	// 聚会未通过

		$list = $this->meeting_model->limit($start,$limit)->where($where)->order('meeting_id desc')->select();

		foreach ($list as $key => $value){
			$list[$key]['meeting_start_time'] = date('Y.m.d H:i',$value['meeting_start_time']); //开始时间,5月20日 19:00
			$list[$key]['meeting_end_time'] = date('Y.m.d H:i',$value['meeting_end_time']);   			 //结束时间,23:00
			//用户信息
			$user_id = $value['user_id'];
			$user = \User\Lib\ImiLib::getUserById($user_id);
			$list[$key]['user_info'] = $user;
			//店铺信息
			$shop_id  = $value['address_id'];;
			$list[$key]['shop_info'] = \Shop\Lib\ImiLib::getShopById($shop_id);
		}


		// 判断返回结果
		if ($list) {
			$arr['status'] = '1';
			$arr['msg'] = '获取活动列表 成功！';
			$arr['info'] = $list;
		} else {
			$arr['status'] = '0';
			$arr['msg'] = '获取活动列表 失败！';
		}
		$this->output($arr);
	}

	/**
	 * 报名参加活动
	 * @author Hongwei 2017-06-17
	 */
	public  function join_meeting(){
		// 得到参数
		$meeting_id = I('meeting_id');		//聚会ID
		$user_mobile = I('user_mobile'); 	//报名参加人的手机号
		$user_name = I('user_name'); 		//报名参加人的姓名

		// 增加的data
		$data['user_id'] 		= 	\User\Lib\ImiLib::getCurrentUserId();
		$data['meeting_id'] 	= 	$meeting_id;		// 聚会ID
		$data['user_mobile'] 	= 	$user_mobile;
		$data['user_name'] 	= 	$user_name;
		$data['user_joined_time'] = time();

		// 查询是否参加过活动的操作
		$where['meeting_id']  		= $meeting_id;
		$where['user_mobile']  	= $user_mobile;
		$where['user_name']  		= $user_name;
		$exist_meeting = $this->meeting_joined_model->where($where)->find();

		if(empty($exist_meeting)){
			// 增加操作
			$rst = $this->meeting_joined_model->add($data);
			// 判断返回结果
			if ($rst) {
				$arr['status'] = '1';
				$arr['msg'] = '报名参加活动 成功！';
				$arr['info'] = $rst;

				// 报名成功后通知发起人 推送/start
				$push_title = '《51聚》聚会报名';		//通知标题
				$participant = $user_mobile; 		//通知内容——报名人手机号
				$meeting_details = \Meeting\Lib\MeetingLib::getDetailsByMeetingId($meeting_id);
				$originator_uid = $meeting_details['user_id'];  		//通知内容——发起人的ID
				$meeting_name = $meeting_details['meeting_title']; 	//通知内容——活动名称
				\Push\Lib\PushLib::push_message($push_title,'用户#'.$participant.'#，报名参加《'.$meeting_name.'》成功！',array('type'=>'system_message','notice_id'=>4),$originator_uid);
				// 报名成功后通知发起人 推送/end
			} else {
				$arr['status'] = '0';
				$arr['msg'] = '报名参加活动 失败！';
			}
		}else{
			$arr['status'] = '2';
			$arr['msg'] = '你已经参加过该活动了！';
		}

		$this->output($arr);

	}

	/**
	 * 本次聚会报名的人
	 */
	public  function  signMeetingPeople(){

		$where[meeting_id] =  	I('meeting_id');		// 聚会ID
		$rst = $this->meeting_joined_model->where($where)->select();
		foreach ($rst as $key => $value){
			// 手机号中间四位变为星号
			$rst[$key]['user_mobile'] = substr_replace($value['user_mobile'],'****',3,4);
			// 增加用户信息
			$user_id = $value['user_id'];
			$user = \User\Lib\ImiLib::getUserById($user_id);
			$rst[$key]['user_info'] = $user;
		}

		// 判断返回结果
		if ($rst) {
			$arr['status'] = '1';
			$arr['msg'] = '本次聚会报名的人 成功！';
			$arr['info'] = $rst;
		} else {
			$arr['status'] = '0';
			$arr['msg'] = '本次聚会报名的人 失败！';
		}
		$this->output($arr);
	}

	/**
	 * 我发起的活动
	 */
	public function  iLaunchMeeting(){
		$user = session('user');
		$where['user_id'] = $user['id'];
		$list = $this->meeting_joined_model->where($where)->select();
		// 判断返回结果
		if ($list) {
			$arr['status'] = '1';
			$arr['msg'] = '获取我发起的活动列表 成功！';
			$arr['info'] = $list;
		} else {
			$arr['status'] = '0';
			$arr['msg'] = '获取我发起的活动列表 失败！';
		}
		$this->output($arr);

	}

	/**
	 * 我参与的活动
	 */
	public function iTakePartInMeeting(){
		$user = session('user');
		$where['user_id'] = $user['id'];
		$list = $this->meeting_joined_model->where($where)->select();
		// 判断返回结果
		if ($list) {
			$arr['status'] = '1';
			$arr['msg'] = '获取我参与的活动列表 成功！';
			$arr['info'] = $list;
		} else {
			$arr['status'] = '0';
			$arr['msg'] = '获取我参与的活动列表 失败！';
		}
		$this->output($arr);
	}

	/**
	 * 搜索活动
	 */
	public  function  searchMeeting(){
		$title = I('keywords');
		if($title){
			$where['title'] = array('LIKE','%'.$title.'%');
		}
		$list = $this->meeting_model->where($where)->select();

		// 判断返回结果
		if ($list) {
			$arr['status'] = '1';
			$arr['msg'] = '搜索活动 成功！';
			$arr['info'] = $list;
		} else {
			$arr['status'] = '0';
			$arr['msg'] = '搜索活动 失败！';
		}
		$this->output($arr);
	}

	/**
	 * 评论活动（不管活动是否开始都可以评论）
	 */
	public function comment_add(){
		
		$meeting_id		= I('meeting_id');
		$comment		= I('comment');
		
		$meeting_info = $this->meeting_model->field('meeting_id,user_id')->find($meeting_id);
		
		if(!$meeting_info){
			$assign['error']	 = 101;
			$assign['error_msg'] = '没有聚会信息';
			$assign['status']	 = false;
			$this->output($assign);
		}
		
		//请求评论接口
		$data = CommentLib::comment_object(MODULE_NAME,$meeting_id,$meeting_info['user_id'],$comment);
		//todo zhangwei 后期使用此方法 增加聚会表中的评论数量
		if($data['status']){
			//聚会表评论数加1
			$result = true && $this->meeting_model->where('meeting_id',$meeting_id)->setInc('comment_number');
			if(!$result){
				$data['status']		= false;
				$data['error']		= 103;
				$data['error_msg']  = '聚会表增加评论失败';
			}
		}
		
		$this->output($data);
	}

	/**
	 *  活动评论列表
	 * @author Hongwei 2017-06-17
	 * TODO 目前只做一级评论，有时间再做多级评论
	 */
	public function comment_list(){
		
		$meeting_id		= I('meeting_id/d');	//活动id
		$offset			= I('offset');
		$limit			= I('limit');
		
		$comment_list = CommentLib::comment_list(MODULE_NAME,$meeting_id,$offset,$limit);
		
		$this->output($comment_list);
	}

	/**
	 * 当前活动共几条评论
	 * @author Hongwei 2017-07-01
	 */
	public function comment_number(){
		$meeting_id		= I('meeting_id/d');	//活动id
		$comment_number = CommentLib::comment_number(MODULE_NAME,$meeting_id);
		$this->output($comment_number);
	}

	/**
	 * 对该评论的点赞动作
	 */
	public function  meeting_thumbs_up(){
		
		$comment_id =  I('comment_id');
		//请求点赞接口
		$data = PraiseLib::praise_comment($comment_id);
		
		$this->output($data);
	}


	/**
	 * 活动支付-虚拟物品
	 */
	public  function meeting_pay(){
		echo "支付完了再说！此项目没有需求！待有需求再增加！";exit;
	}


}

